package com.artisan.view;

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Vector;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import com.artisan.dao.CourseDao;
import com.artisan.dao.ScoreDao;
import com.artisan.dao.SelectedCourseDao;
import com.artisan.dao.StudentDao;
import com.artisan.model.Course;
import com.artisan.model.Score;
import com.artisan.model.Student;
import com.artisan.model.Teacher;

public class ManageScoreFrm extends JInternalFrame {
	private JTable scoreListTable;
	private JTextField editScoreTextField;
	private JComboBox studentComboBox;
	private JComboBox courseComboBox;
	private List<Student> studentList;
	private List<Course> courseList;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ManageScoreFrm frame = new ManageScoreFrm();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ManageScoreFrm() {
		setClosable(true);
		setIconifiable(true);

		getContentPane().setFont(new Font("微软雅黑", Font.PLAIN, 14));
		setFrameIcon(new ImageIcon(ManageScoreFrm.class.getResource("/com/artisan/image/成绩.png")));
		setTitle("成绩管理界面");
		setBounds(100, 100, 748, 497);

		JLabel lblNewLabel = new JLabel("学生姓名:");
		lblNewLabel.setIcon(new ImageIcon(ManageScoreFrm.class.getResource("/com/artisan/image/学生管理.png")));
		lblNewLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		studentComboBox = new JComboBox();

		JLabel lblNewLabel_1 = new JLabel("课程名称:");
		lblNewLabel_1.setIcon(new ImageIcon(ManageScoreFrm.class.getResource("/com/artisan/image/课程.png")));
		lblNewLabel_1.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		courseComboBox = new JComboBox();
		courseComboBox.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent ie) {
				courseChangedAct(ie);
			}
		});

		JButton searchButton = new JButton("查询");
		searchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				Student student = (Student) studentComboBox.getSelectedItem();
				Course course = (Course) courseComboBox.getSelectedItem();
				Score score = new Score();
				score.setStudent_id(student.getId());
				score.setCourse_id(course.getId());
				setTable(score);
			}
		});
		searchButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		searchButton.setIcon(new ImageIcon(ManageScoreFrm.class.getResource("/com/artisan/image/搜索.png")));

		JScrollPane scrollPane = new JScrollPane();

		JPanel panel = new JPanel();
		panel.setBorder(
				new TitledBorder(null, "\u4FEE\u6539\u6210\u7EE9", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout
				.createSequentialGroup().addGap(71)
				.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
						.addComponent(panel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
								GroupLayout.PREFERRED_SIZE)
						.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
								.addComponent(scrollPane, Alignment.LEADING)
								.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
										.addComponent(lblNewLabel).addPreferredGap(ComponentPlacement.RELATED)
										.addComponent(studentComboBox, GroupLayout.PREFERRED_SIZE, 109,
												GroupLayout.PREFERRED_SIZE)
										.addGap(33).addComponent(lblNewLabel_1)
										.addPreferredGap(ComponentPlacement.UNRELATED)
										.addComponent(courseComboBox, GroupLayout.PREFERRED_SIZE, 119,
												GroupLayout.PREFERRED_SIZE)
										.addGap(41).addComponent(searchButton, GroupLayout.PREFERRED_SIZE, 97,
												GroupLayout.PREFERRED_SIZE))))
				.addContainerGap(87, Short.MAX_VALUE)));
		groupLayout
				.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup().addGap(35)
								.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(lblNewLabel)
										.addComponent(studentComboBox, GroupLayout.PREFERRED_SIZE,
												GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
										.addComponent(lblNewLabel_1)
										.addComponent(courseComboBox, GroupLayout.PREFERRED_SIZE,
												GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
										.addComponent(searchButton))
								.addGap(18)
								.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 274, GroupLayout.PREFERRED_SIZE)
								.addGap(18)
								.addComponent(panel, GroupLayout.PREFERRED_SIZE, 65, GroupLayout.PREFERRED_SIZE)
								.addContainerGap(31, Short.MAX_VALUE)));

		JLabel lblNewLabel_2 = new JLabel("所得成绩:");
		lblNewLabel_2.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		lblNewLabel_2.setIcon(new ImageIcon(ManageScoreFrm.class.getResource("/com/artisan/image/成绩.png")));

		editScoreTextField = new JTextField();
		editScoreTextField.setColumns(10);

		JButton confirmEditButton = new JButton("确认修改");
		confirmEditButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent se) {
				editSubmitAct(se);
			}
		});
		confirmEditButton.setIcon(new ImageIcon(ManageScoreFrm.class.getResource("/com/artisan/image/确认.png")));
		confirmEditButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		JButton deleteButton = new JButton("删除成绩");
		deleteButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent de) {
				deleteAct(de);
			}
		});
		deleteButton.setIcon(new ImageIcon(ManageScoreFrm.class.getResource("/com/artisan/image/删除.png")));
		deleteButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup().addGap(21).addComponent(lblNewLabel_2)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(editScoreTextField, GroupLayout.PREFERRED_SIZE, 126, GroupLayout.PREFERRED_SIZE)
						.addGap(37).addComponent(confirmEditButton).addGap(28).addComponent(deleteButton)
						.addContainerGap(50, Short.MAX_VALUE)));
		gl_panel.setVerticalGroup(gl_panel.createParallelGroup(Alignment.LEADING).addGroup(gl_panel
				.createSequentialGroup()
				.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE).addComponent(lblNewLabel_2)
						.addComponent(editScoreTextField, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)
						.addComponent(deleteButton, GroupLayout.PREFERRED_SIZE, 29, GroupLayout.PREFERRED_SIZE)
						.addComponent(confirmEditButton, GroupLayout.PREFERRED_SIZE, 29, GroupLayout.PREFERRED_SIZE))
				.addContainerGap(39, Short.MAX_VALUE)));
		panel.setLayout(gl_panel);

		scoreListTable = new JTable();
		scoreListTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent me) {
				tableItemClick(me);
			}
		});
		scoreListTable.setModel(new DefaultTableModel(new Object[][] {}, new String[] { "\u6210\u7EE9ID",
				"\u5B66\u751F\u59D3\u540D", "\u8BFE\u7A0B\u540D\u79F0", "\u6240\u5F97\u6210\u7EE9" }) {
			boolean[] columnEditables = new boolean[] { false, false, false, false };

			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		scoreListTable.getColumnModel().getColumn(1).setPreferredWidth(74);
		scoreListTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		scrollPane.setViewportView(scoreListTable);
		getContentPane().setLayout(groupLayout);
		setCourseCombox();
		setStudentCombox();
		initTable();
	}

	protected void deleteAct(ActionEvent de) {
		// TODO 自动生成的方法存根
		int row = scoreListTable.getSelectedRow();
		if (row == -1) {
			JOptionPane.showMessageDialog(this, "请先选择一行!");
			return;
		}
		if (JOptionPane.showConfirmDialog(this, "确定要删除吗?", "删除提示", 0) == JOptionPane.OK_OPTION) {
			int scoreId = Integer.parseInt(scoreListTable.getValueAt(row, 0).toString());
			ScoreDao scoreDao = new ScoreDao();
			if (scoreDao.delete(scoreId)) {
				JOptionPane.showMessageDialog(this, "删除成功!");
				editScoreTextField.setText("");
				initTable();
			} else {
				JOptionPane.showMessageDialog(this, "删除失败!");
			}
			scoreDao.closeDao();
		}
	}

	protected void editSubmitAct(ActionEvent se) {
		// TODO 自动生成的方法存根
		int row = scoreListTable.getSelectedRow();
		if (row == -1) {
			JOptionPane.showMessageDialog(this, "请先选择一行!");
			return;
		}
		int scoreId = Integer.parseInt(scoreListTable.getValueAt(row, 0).toString());
		int score = Integer.parseInt(editScoreTextField.getText().toString());
		ScoreDao scoreDao = new ScoreDao();
		if (scoreDao.update(scoreId, score)) {
			JOptionPane.showMessageDialog(this, "更新成功!");
			editScoreTextField.setText("");
			initTable();
		} else {
			JOptionPane.showMessageDialog(this, "更新失败!");
		}
		scoreDao.closeDao();
	}

	protected void tableItemClick(MouseEvent me) {
		// TODO 自动生成的方法存根
		String score = (scoreListTable.getValueAt(scoreListTable.getSelectedRow(), 3).toString());
		editScoreTextField.setText(score);
	}

	protected void courseChangedAct(ItemEvent ie) {
		// TODO 自动生成的方法存根
		if (ie.getStateChange() == ItemEvent.SELECTED) {
			setStudentCombox();
		}
	}

	private void setStudentCombox() {
		studentComboBox.removeAllItems();
		StudentDao studentDao = new StudentDao();
		studentList = studentDao.getStudentList(new Student());
		studentDao.closeDao();
		Course course = (Course) courseComboBox.getSelectedItem();
		List<Student> selectedCourseStudentList = getSelectedCourseStudentList(course);
		for (Student student : studentList) {
			for (Student student2 : selectedCourseStudentList) {
				if (student.getId() == student2.getId()) {
					studentComboBox.addItem(student);
				}
			}
		}
	}

	private void setCourseCombox() {
		CourseDao courseDao = new CourseDao();
		courseList = courseDao.getCourseList(new Course());
		courseDao.closeDao();
		for (Course course : courseList) {
			if ("教师".equals(MainFrm.userType.getName())) {
				Teacher teacher = (Teacher) MainFrm.userObject;
				if (course.getTeacher_id() == teacher.getId()) {
					courseComboBox.addItem(course);
				}
				continue;
			}
			// 执行到这里一定是管理员身份
			courseComboBox.addItem(course);
		}
	}

	private void initTable() {
		getScoreList(new Score());
	}

	private void setTable(Score score) {
		getScoreList(score);
	}

	private void getScoreList(Score score) {
		ScoreDao scoreDao = new ScoreDao();
		List<Score> scoreList = scoreDao.getScoreList(score);
		DefaultTableModel dft = (DefaultTableModel) scoreListTable.getModel();
		dft.setRowCount(0);
		for (Score s : scoreList) {
			Vector v = new Vector();
			v.add(s.getId());
			v.add(getStudentNameById(s.getStudent_id()));
			v.add(getCourseById(s.getCourse_id()));
			v.add(s.getScore());
			dft.addRow(v);
		}
		scoreDao.closeDao();
	}

	private Course getCourseById(int id) {
		for (int i = 0; i < courseList.size(); i++) {
			if (id == courseList.get(i).getId()) {
				return courseList.get(i);
			}
		}
		return null;
	}

	private List<Student> getSelectedCourseStudentList(Course course) {
		SelectedCourseDao scDao = new SelectedCourseDao();
		List<Student> selectedCourseStudentList = scDao.getSelectedCourseStudentList(course);
		return selectedCourseStudentList;
	}

	private String getStudentNameById(int id) {
		for (Student student : studentList) {
			if (student.getId() == id) {
				return student.getName();
			}
		}
		return null;
	}
}
